package nuc.soft.xsf.serviceImpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import nuc.soft.xsf.dao.impl.UserDaoImpl;
import nuc.soft.xsf.model.Filesystem;
import nuc.soft.xsf.service.IFilesystemService;
import nuc.soft.xsf.service.IUserService;

@Service
public class UserServiceImpl extends UserDaoImpl implements IUserService{

	@Resource
	private IFilesystemService filedao;
	
	@Override
	public String uploadFile(MultipartFile upfile,HttpServletRequest request) {
		// TODO Auto-generated method stub
		try{		
		Filesystem filesystem=new Filesystem();
		String uuid = UUID.randomUUID().toString();
		filesystem.setId(uuid);
		String oldname=upfile.getOriginalFilename();
		filesystem.setName(oldname);
		filesystem.setOldname(oldname);
		filesystem.setState(1);
		filesystem.setUptime(this.getNowTime_Format());
		filesystem.setFiletype(oldname.substring(oldname.lastIndexOf(".")));
		String basepath=request.getRealPath("/");
		FileInputStream fis=(FileInputStream) upfile.getInputStream();
		String wantname="file_"+filesystem.getId();
		String saveurl=this.upfile(fis, oldname, basepath,"img",wantname);
		filesystem.setSaveurl(saveurl);
		filesystem.setNewname(wantname);
		filedao.insert(filesystem);
		return filesystem.getSaveurl();
		
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return null;
	}
	
	
	private  String getNowTime_Format() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss");
		return sdf.format(new Date());
	}
	
	private String  upfile(FileInputStream fis, String uploadfilename,
			String basepath, String savepath, String wantnewname) {
		String oldname = uploadfilename;
		String newname = getNowTime_Format()+"_"+oldname.substring(oldname.lastIndexOf("."));
		try {
			File outfile = null;
			if (wantnewname == null || wantnewname.equals("")) {
				outfile = new File(basepath + "/" + savepath + "/" + "test"
						+ newname);
			} else {
				newname = wantnewname + newname;
				outfile = new File(basepath + "/" + savepath + "/" + newname);
			}

			if (!outfile.exists()) {
				outfile.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(outfile);
			byte b[] = new byte[1024];
			int len = 0;
			while ((len = fis.read(b)) > 0) {
				fos.write(b, 0, len);
			}
			fos.close();
			fis.close();
			return savepath + "/" + newname;
		} catch (Exception ex) {
			ex.printStackTrace();			
		}
		return null;
	}

}
